uniapp通过WebSocket与设备通讯 您所在的位置:网站首页 uni-app websocket消息过长 uniapp通过WebSocket与设备通讯

uniapp通过WebSocket与设备通讯

2023-04-21 20:23| 来源: 网络整理| 查看: 265

连接 发送 关闭 清除数据 {{e}} export default { data() { return { isLogin: false, url: 'ws://192.168.4.1:9988', ST: false, isOpen: false, timer: null, message: [] } }, onLoad() { this.open() }, methods: { open() { this.closeSocket(); this.ST = uni.connectSocket({ url: this.url, complete: (e) => {}, fail: (f) => { console.log(f); }, success: (s) => { console.log(this.ST); if (!this.ST) { console.log(this.ST); return //防止错误open } uni.onSocketOpen((res) => { console.log('WebSocket连接已打开!'); this.isLogin = true console.log('连接成功'); }); uni.onSocketMessage((res) => { console.log('接收到服务端发送的消息', res.data); this.message.push(res.data); }) uni.onSocketOpen(function(res) { console.log('WebSocket连接已打开!'); }); uni.onSocketClose((res) => { console.log(res); if (!this.ST) { return; } uni.showToast({ title: '与服务器连接中断,请重新刷新页面!', icon: 'loading' }) clearInterval(this.t1); this.isLogin = false this.ST = false; this.timer = setTimeout(() => { this.open() }, 5000) }); uni.onSocketError((res) => { if (!this.ST) { return; } uni.showToast({ title: '与服务器连接错误,请重新刷新页面!', icon: 'loading' }) this.isLogin = false this.ST = false this.timer = setTimeout(() => { this.open() }, 5000) }); } }); }, //发送消息 sendMessage(msg) { uni.sendSocketMessage({ data: msg, success(res) { console.log(res); console.log('消息发送成功!') }, fail(err) { console.log(err); console.log('消息发送失败!') } }) }, //关闭连接 closeSocket() { //关闭socket连接 this.ST = false; clearTimeout(this.timer); uni.closeSocket({ success(res) { this.is_open_socket = false; console.log("关闭成功", res) }, fail(err) { console.log("关闭失败", err) } }); } } } .content { display: flex; flex-direction: column; align-items: center; justify-content: center; } button { margin: 10rpx 0; } .data { border: 1rpx solid #000; width: 90%; padding: 10rpx; margin: 10rpx auto; box-sizing: border-box; view { padding: 10rpx; } } 复制代码

客户端与服务端必须连接同一个wifi



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有